package com.autoboot.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus配置类
 * @author Maosw
 */
@Configuration
public class MybatisPlusConfig {

    @Autowired
    private AutoBootProperties properties;

    /**
     * 配置分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 配置自动填充处理器
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                if (properties.getDb().isAutoFillTime()) {
                    this.strictInsertFill(metaObject, properties.getDb().getCreateTimeField(), LocalDateTime.class, LocalDateTime.now());
                    this.strictInsertFill(metaObject, properties.getDb().getUpdateTimeField(), LocalDateTime.class, LocalDateTime.now());
                }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                if (properties.getDb().isAutoFillTime()) {
                    this.strictUpdateFill(metaObject, properties.getDb().getUpdateTimeField(), LocalDateTime.class, LocalDateTime.now());
                }
            }
        };
    }
}
